/**
 * MapVerse 地图管理器
 * @description 提供统一的地图实例管理和操作接口
 */

/**
 * 地图管理器类
 */
class MapManager {
  constructor() {
    this.instances = new Map();
    this.eventBus = new Map();
  }

  /**
   * 注册地图实例
   * @param {string} mapId - 地图ID
   * @param {Object} instance - MapVerse实例
   */
  register(mapId, instance) {
    this.instances.set(mapId, instance);
    
    // 触发注册事件
    this.emit('register', { mapId, instance });
    console.log(`MapVerse实例已注册: ${mapId}`);
  }

  /**
   * 注销地图实例
   * @param {string} mapId - 地图ID
   */
  unregister(mapId) {
    const instance = this.instances.get(mapId);
    if (instance) {
      this.instances.delete(mapId);
      this.emit('unregister', { mapId, instance });
      console.log(`MapVerse实例已注销: ${mapId}`);
    }
  }

  /**
   * 获取地图实例
   * @param {string} mapId - 地图ID
   * @returns {Object|null} MapVerse实例
   */
  getInstance(mapId) {
    return this.instances.get(mapId) || null;
  }

  /**
   * 检查实例是否存在
   * @param {string} mapId - 地图ID
   * @returns {boolean}
   */
  hasInstance(mapId) {
    return this.instances.has(mapId);
  }

  /**
   * 获取所有实例ID
   * @returns {Array<string>}
   */
  getAllInstanceIds() {
    return Array.from(this.instances.keys());
  }

  /**
   * 等待实例初始化完成
   * @param {string} mapId - 地图ID
   * @param {number} timeout - 超时时间（毫秒）
   * @returns {Promise<Object>} MapVerse实例
   */
  waitForInstance(mapId, timeout = 5000) {
    return new Promise((resolve, reject) => {
      // 如果实例已存在，直接返回
      const instance = this.getInstance(mapId);
      if (instance) {
        resolve(instance);
        return;
      }

      // 设置超时
      const timer = setTimeout(() => {
        this.off('register', onRegister);
        reject(new Error(`等待地图实例超时: ${mapId}`));
      }, timeout);

      // 监听注册事件
      const onRegister = ({ mapId: registeredId, instance }) => {
        if (registeredId === mapId) {
          clearTimeout(timer);
          this.off('register', onRegister);
          resolve(instance);
        }
      };

      this.on('register', onRegister);
    });
  }

  /**
   * 事件监听
   * @param {string} event - 事件名称
   * @param {Function} callback - 回调函数
   */
  on(event, callback) {
    if (!this.eventBus.has(event)) {
      this.eventBus.set(event, []);
    }
    this.eventBus.get(event).push(callback);
  }

  /**
   * 移除事件监听
   * @param {string} event - 事件名称
   * @param {Function} callback - 回调函数
   */
  off(event, callback) {
    const callbacks = this.eventBus.get(event);
    if (callbacks) {
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
    }
  }

  /**
   * 触发事件
   * @param {string} event - 事件名称
   * @param {any} data - 事件数据
   */
  emit(event, data) {
    const callbacks = this.eventBus.get(event);
    if (callbacks) {
      callbacks.forEach(callback => {
        try {
          callback(data);
        } catch (error) {
          console.error(`MapManager事件回调错误 [${event}]:`, error);
        }
      });
    }
  }

  // === 便捷操作方法 ===

  /**
   * 添加矢量塔位
   * @param {string} mapId - 地图ID
   * @param {Object} options - 塔位配置
   * @returns {Promise<boolean>} 操作结果
   */
  async addVectorTower(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.businessLayers?.addVectorTower(options);
      return true;
    } catch (error) {
      console.error(`添加矢量塔位失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 添加矢量线路
   * @param {string} mapId - 地图ID
   * @param {Object} options - 线路配置
   * @returns {Promise<boolean>} 操作结果
   */
  async addVectorLine(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.businessLayers?.addVectorLine(options);
      return true;
    } catch (error) {
      console.error(`添加矢量线路失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 添加矢量变电站
   * @param {string} mapId - 地图ID
   * @param {Object} options - 变电站配置
   * @returns {Promise<boolean>} 操作结果
   */
  async addVectorSubStation(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.businessLayers?.addVectorSubStation(options);
      return true;
    } catch (error) {
      console.error(`添加矢量变电站失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 移除矢量
   * @param {string} mapId - 地图ID
   * @param {string} vectorId - 矢量ID
   * @returns {Promise<boolean>} 操作结果
   */
  async removeVectorById(mapId, vectorId) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.businessLayers?.removeVectorById(vectorId);
      return true;
    } catch (error) {
      console.error(`移除矢量失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 添加面矢量图层
   * @param {string} mapId - 地图ID
   * @param {Object} options - 面矢量配置
   * @returns {Promise<boolean>} 操作结果
   */
  async addPolygonJson(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.businessLayers?.addPolygonJson(options);
      return true;
    } catch (error) {
      console.error(`添加面矢量图层失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 添加线矢量图层
   * @param {string} mapId - 地图ID
   * @param {Object} options - 线矢量配置
   * @returns {Promise<boolean>} 操作结果
   */
  async addPolylineJson(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.businessLayers?.addPolylineJson(options);
      return true;
    } catch (error) {
      console.error(`添加线矢量图层失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 添加点矢量图层
   * @param {string} mapId - 地图ID
   * @param {Object} options - 点矢量配置
   * @returns {Promise<boolean>} 操作结果
   */
  async addPointJson(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.businessLayers?.addPointJson(options);
      return true;
    } catch (error) {
      console.error(`添加点矢量图层失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 添加WMS图层
   * @param {string} mapId - 地图ID
   * @param {Object} options - WMS配置
   * @returns {Promise<Object|null>} 图层实例
   */
  async addWmsLayer(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      return instance.addWmsLayer?.(options) || null;
    } catch (error) {
      console.error(`添加WMS图层失败 [${mapId}]:`, error);
      return null;
    }
  }

  /**
   * 添加敏感区分析图层
   * @param {string} mapId - 地图ID
   * @param {Object} options - 敏感区分析图层配置
   * @returns {Promise<Object|null>} 敏感区分析图层实例
   */
  async addSensitiveAnalyseLayer(mapId, options) {
    try {
      const instance = await this.waitForInstance(mapId);
      return instance.businessLayers?.addSensitiveAnalyseLayer(options) || null;
    } catch (error) {
      console.error(`添加敏感区分析图层失败 [${mapId}]:`, error);
      return null;
    }
  }

  /**
   * 飞行到指定位置
   * @param {string} mapId - 地图ID
   * @param {number} lng - 经度
   * @param {number} lat - 纬度
   * @param {Object} options - 飞行配置
   * @returns {Promise<boolean>} 操作结果
   */
  async flyToPoint(mapId, lng, lat, options = {}) {
    try {
      const instance = await this.waitForInstance(mapId);
      instance.flyToPoint?.(lng, lat, options);
      return true;
    } catch (error) {
      console.error(`飞行到位置失败 [${mapId}]:`, error);
      return false;
    }
  }

  /**
   * 获取地图实例
   * @param {string} mapId - 地图ID
   * @returns {Promise<Object|null>} 地图实例
   */
  async getMapInstance(mapId) {
    try {
      const instance = await this.waitForInstance(mapId);
      return instance.getMapInstance?.() || null;
    } catch (error) {
      console.error(`获取地图实例失败 [${mapId}]:`, error);
      return null;
    }
  }
}

// 创建全局单例
const mapManager = new MapManager();

// 自动与window对象同步
if (typeof window !== 'undefined') {
  // 监听window对象上的MapVerse实例变化
  const originalDefineProperty = Object.defineProperty;
  const mapVerseInstances = {};
  
  // 代理window对象上的mapVerse实例
  const proxyWindow = new Proxy(window, {
    set(target, key, value) {
      if (typeof key === 'string' && key.startsWith('mapVerse_')) {
        const mapId = key.replace('mapVerse_', '');
        if (value) {
          mapManager.register(mapId, value);
          mapVerseInstances[mapId] = value;
        } else {
          mapManager.unregister(mapId);
          delete mapVerseInstances[mapId];
        }
      }
      return Reflect.set(target, key, value);
    },
    
    deleteProperty(target, key) {
      if (typeof key === 'string' && key.startsWith('mapVerse_')) {
        const mapId = key.replace('mapVerse_', '');
        mapManager.unregister(mapId);
        delete mapVerseInstances[mapId];
      }
      return Reflect.deleteProperty(target, key);
    }
  });
  
  // 检查已存在的实例
  Object.keys(window).forEach(key => {
    if (key.startsWith('mapVerse_')) {
      const mapId = key.replace('mapVerse_', '');
      const instance = window[key];
      if (instance) {
        mapManager.register(mapId, instance);
      }
    }
  });
}

export default mapManager;

/**
 * 组合式API - 使用地图管理器
 * @param {string} mapId - 地图ID
 * @returns {Object} 地图操作API
 */
export function useMapManager(mapId) {
  return {
    // 实例管理
    getInstance: () => mapManager.getInstance(mapId),
    waitForInstance: (timeout) => mapManager.waitForInstance(mapId, timeout),
    hasInstance: () => mapManager.hasInstance(mapId),
    
    // 便捷操作 - 业务图层
    addVectorTower: (options) => mapManager.addVectorTower(mapId, options),
    addVectorLine: (options) => mapManager.addVectorLine(mapId, options),
    addVectorSubStation: (options) => mapManager.addVectorSubStation(mapId, options),
    removeVectorById: (vectorId) => mapManager.removeVectorById(mapId, vectorId),
    
    // 便捷操作 - 监测结果矢量
    addPolygonJson: (options) => mapManager.addPolygonJson(mapId, options),
    addPolylineJson: (options) => mapManager.addPolylineJson(mapId, options),
    addPointJson: (options) => mapManager.addPointJson(mapId, options),
    addWmsLayer: (options) => mapManager.addWmsLayer(mapId, options),
    // 便捷操作 - 敏感区矢量
    addSensitiveAnalyseLayer: (options) => mapManager.addSensitiveAnalyseLayer(mapId, options),
    
    // 地图控制
    flyToPoint: (lng, lat, options) => mapManager.flyToPoint(mapId, lng, lat, options),
    getMapInstance: () => mapManager.getMapInstance(mapId),
    
    // 事件系统
    onReady: (callback) => {
      if (mapManager.hasInstance(mapId)) {
        callback(mapManager.getInstance(mapId));
      } else {
        const onRegister = ({ mapId: registeredId, instance }) => {
          if (registeredId === mapId) {
            mapManager.off('register', onRegister);
            callback(instance);
          }
        };
        mapManager.on('register', onRegister);
      }
    }
  };
}
